﻿using System;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Portal.Models;
using SoEasyPlatform.LayUiExample.Enties.DbModels;

namespace Portal.Controllers
{
    public class MyBaseController : Controller
    {

        private readonly IHostEnvironment _hostingEnvironment;
        public MyBaseController(IHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 当前登录用户
        /// </summary>
        public sys_user LoginUser
        {
            get
            {
                var curLoginUserStr = HttpContext.Session.GetString(GlobalVariable.LoginUser);
                var curLoginUserObj = JsonConvert.DeserializeObject<sys_user>(curLoginUserStr);
                return curLoginUserObj;
            }
        }

        /// <summary>
        /// 生成文件保存路径
        /// </summary>
        /// <returns></returns>
        public string GenerateFileSavePath(FolderPath saveFolderPath)
        {
            var savePath = $"{_hostingEnvironment.ContentRootPath}\\wwwroot\\DownLoad\\{saveFolderPath}";
            var pathExist = Directory.Exists(savePath);
            if (pathExist == false)
            {
                Directory.CreateDirectory(savePath);
            }
            return savePath;
        }

        /// <summary>
        /// 拼接文件的物理全路径
        /// </summary>
        /// <returns></returns>
        public string CombineFileAllPath(string path, string fileName, FileExtension downLoadFileExtension)
        {
            return Path.Combine(path, $"{fileName}.{downLoadFileExtension}");
        }

        /// <summary>
        /// 本机文件全路径
        /// </summary>
        /// <param name="localFileAllPath"></param>
        /// <returns></returns>
        public string GenerateDownLoadUrl(string localFileAllPath)
        {
            var index = localFileAllPath.LastIndexOf(@"\DownLoad\", StringComparison.Ordinal);
            var curString = localFileAllPath.Substring(index).Replace(@"\","/");
            var downloadUrl = $"{Request.Scheme}://{Request.Host}{curString}";
            return downloadUrl;
        }

        /// <summary>
        /// 生成需要提供下载文件的url路径
        /// </summary>
        /// <returns></returns>
        public string GenerateDownloadUrl(string fileName, FolderPath downLoadFolderPath, FileExtension downLoadFileExtension)
        {
            return $"{Request.Scheme}://{Request.Host}/DownLoad/{downLoadFolderPath}/{fileName}.{downLoadFileExtension}";
        }

        public enum FolderPath
        {
            /// <summary>
            /// excel文件夹
            /// </summary>
            Excel = 1,
        }

        public enum FileExtension
        {
            /// <summary>
            /// excel文件扩展名
            /// </summary>
            Xlsx = 1,
        }
    }
}